package com.chinaedu.oc.action.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.chinaedu.oc.util.common.IdCreater;

@Controller
@RequestMapping("/file")
public class FileUploadAction {
	
	@RequestMapping("/upload")
	@ResponseBody
	public Map<String, Object> get(@RequestParam("file")CommonsMultipartFile upfile,HttpServletRequest request, HttpServletResponse response) {
		try {

			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			
			String fileName = upfile.getFileItem().getName();
			System.out.println("fileName:"+fileName);
			String newName = IdCreater.getId()+fileName.substring(upfile.getOriginalFilename().lastIndexOf("."));
			
			String filepath = "/upload"+new SimpleDateFormat("yyyyMMdd").format(new Date());
			
			String path = request.getSession().getServletContext().getRealPath(filepath); //+ newName;
			File f = new File(path);
			if(!f.exists()) {
				f.mkdirs();
			}
			
			path += "/" + newName;
			
			System.out.println(path);
			InputStream is = upfile.getInputStream();
			byte[] b = new byte[is.available()];
			is.read(b);
			FileOutputStream fos = new FileOutputStream(new File(path));
			fos.write(b);
			fos.flush();
			fos.close();
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("url", filepath + "/" +newName);
			map.put("code", 0);
			
			return map;
			
			

		} catch (IOException e) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", 1);
			
			return map;
		}
	}
}
